#include "../inc/my_mblog_widget.h"
#include "my_mblog_item.h"

my_mblog_widget::my_mblog_widget(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
	this->limit=10;
	this->offset=0;
}

my_mblog_widget::~my_mblog_widget()
{

}

void my_mblog_widget::ReadNews(const int _limit,const int _offset,const bool _fresh){
	this->limit=_limit;
	this->offset=_offset;
	QUrl u(UserHomePageUrl);
	u.addQueryItem("limit",QUrl::toPercentEncoding(QString::number(limit)));
	u.addQueryItem("offset",QUrl::toPercentEncoding(QString::number(offset)));
	u.addQueryItem("token",QUrl::toPercentEncoding(dt::Token()));
	u.addQueryItem("guid",QUrl::toPercentEncoding(dt::UserGuid()));
	#ifdef _USE_MID_PAGE_
	QString _u=u.toString();
	u=QUrl(_MID_PAGE_);
	u.addQueryItem("url",QUrl::toPercentEncoding(_u));
	#endif
	if(!_fresh){
		QString xml=dt::Get(u.toString(),"");
		if(xml!=""){
			this->ReadXml(xml);
			return;
		}
	}
	dh=new DtHttp(u,GET,this);
	connect(dh->Send(),SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(QNetworkReply*)));
}

void my_mblog_widget::SetSoftKeys(QWidget *parent){
	this->my_parent=parent;
//ui.centralwidget->setContextMenuPolicy(Qt::NoContextMenu);
	this->actRef = new QAction(tr("Refresh1"), this->my_parent);
	actRef->setSoftKeyRole(QAction::PositiveSoftKey);
	this->my_parent->addAction(actRef);
	connect(actRef, SIGNAL(triggered()), this, SLOT(OnSkRef()));
}

void my_mblog_widget::OnSkRef(){
	QMessageBox::critical(this,
							  "error",
							  "network fail",
							  QMessageBox::Ok);
	this->ReadNews(10,0);
}

void my_mblog_widget::Refresh(){
	this->ReadNews(10,0,true);
}

void my_mblog_widget::finished(QNetworkReply *reply){
	if(reply->error() == QNetworkReply::NoError)
	{
		QString xml=reply->readAll();
		dt::Set(reply->url().toString(),xml);
		this->ReadXml(xml);
	}
	else
	{
		QMessageBox::critical(this,
								  "error",
								  "network fail",
								  QMessageBox::Ok);
		return;
	}
}

void my_mblog_widget::ReadXml(const QString& xml){
	QDomDocument doc("mydocument"); 
	if (!doc.setContent(xml,false)) 
	{        
		QMessageBox::critical(this,
							  "error",
							  "network fail",
							  QMessageBox::Ok);  
		return;      
	}
	QDomElement ele;
    QDomElement docElem = doc.documentElement(); 
	QDomElement eleEr=docElem.firstChildElement("error");
	ele=eleEr.firstChildElement("code");
	if(ele.text().trimmed()=="1"){
		QString desc=eleEr.firstChildElement("desc").text();
		QMessageBox::critical(this,
							  "fail",
							  desc,
							  QMessageBox::Ok);  
		return;  
	}
	QDomNodeList nodeList = docElem.elementsByTagName("mblog");
	this->ui.lwMblogs->clear();
	for(int ii = 0;ii < nodeList.count(); ii++)
	{
		QDomElement mb = nodeList.at(ii).toElement();
		my_mblog_item* mmi=new my_mblog_item();
		mmi->InitMblog(mb);
		QListWidgetItem *lwiMblog=new QListWidgetItem(this->ui.lwMblogs);
		lwiMblog->setSizeHint(QSize(360,77)); 
		this->ui.lwMblogs->setItemWidget(lwiMblog,mmi);
	}
}
